﻿using System;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Reflection;
using JetBrains.Annotations;
using Kaleida.ServiceMonitor.Model;

namespace Kaleida.ServiceMonitor.UI
{
    public class FileBasedConfiguration : IConfiguration
    {
        public int MaximumResponses
        {
            get { return ReadLowerBoundedInteger("MaximumResponses", 1); }
        }

        public int MaximumErrors
        {
            get { return ReadLowerBoundedInteger("MaximumErrors", 1); }
        }

        [CanBeNull]
        public string InitialScriptName
        {
            get { return ConfigurationManager.AppSettings["InitialScriptName"]; }
        }

        public bool AutoStart
        {
            get { return Convert.ToBoolean(ConfigurationManager.AppSettings["AutoStart"]); }
        }

        [CanBeNull]
        public string SmtpServer
        {
            get { return ConfigurationManager.AppSettings["SmtpServer"]; }
        }

        [CanBeNull]
        public MailAddress EmailSenderAddress
        {
            get
            {
                var emailAddress = ConfigurationManager.AppSettings["EmailSenderAddress"];
                return string.IsNullOrEmpty(emailAddress) ? null : new MailAddress(emailAddress, "ServiceMon");
            }
        }

        public string OperationsPath
        {
            get{return Path.Combine(ExePath, "Operations");}
        }

        public string ScriptsPath
        {
            get { return Path.Combine(ExePath, "Scripts"); }
        }

        private static string ExePath
        {
            get { return Path.GetDirectoryName(Assembly.GetAssembly(typeof (Program)).Location); }
        }

        private static int ReadLowerBoundedInteger(string name, int minimum)
        {
            var value = ReadInteger(name);
            if (value < minimum)
                throw new ConfigurationErrorsException(string.Format("Expected {0} to be {1} or more", name, minimum));

            return value;
        }

        private static int ReadInteger(string name)
        {
            var valueStr = ReadString(name);

            int value;
            if (!int.TryParse(valueStr, out value))
                throw new ConfigurationErrorsException(string.Format("Could not convert {0} value '{1}' into a number", name, valueStr));
            
            return value;
        }

        [NotNull]
        private static string ReadString(string name)
        {
            var valueStr = ConfigurationManager.AppSettings[name];

            if (valueStr == null)
                throw new ConfigurationErrorsException(string.Format("Missing config item: {0}. Please ensure the .config file has an entry in the appSettings section", name));

            return valueStr;
        }
    }
}
